'use strict';

const fs = require('fs');
const Service = require('egg').Service;

const filePath = './app/public/img/mobileScreenshot.png';

function saveFile (filePath, data) {
  return new Promise((resolve, reject) => {
    fs.writeFile(filePath, data, err => {
      if (err) throw err;
      console.log('文件已被保存');
      resolve(true);
    });
  });
}

function readFile (file) {
  const filePath = file.filepath;
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, (err, data) => {
      if (err) throw err;
      resolve(data);
    });
  });
}

function bitmap2Base64 (bitmap) {
  const base64str = Buffer.from(bitmap, 'binary').toString('base64'); // base64编码
  return base64str;
}

class castScreenService extends Service {
  async saveImg () {
    console.log('F:\\egg-castscreen\\app\\service\\castScreen.js');
    console.log('castScreenService.saveImg');
    const { ctx } = this;
    // files[0]表示获取第一个文件，若前端上传多个文件则可以遍历这个数组对象
    // file包含了文件名，文件类型，大小，路径等信息，可以自己打印下看看
    console.log('ctx.request =');
    console.log(ctx.request);
    console.log('ctx.request.files =');
    console.log(ctx.request.files);
    const file = ctx.request.files[0];
    const data = await readFile(file);
    const base64Data = bitmap2Base64(data);
    this.app.io.of('/').emit('updateImg', base64Data);
    await saveFile(filePath, data);
    ctx.cleanupRequestFiles();
    return 'saveFile success';
  }
  async saveImgBase64 () {
    console.log('F:\\egg-castscreen\\app\\service\\castScreen.js');
    console.log('castScreenService.saveImgBase64');
    const { ctx } = this;
    this.app.io.of('/').emit('updateImg', ctx.request.body.base64Data);
    return 'saveImgBase64 success';
  }
}

module.exports = castScreenService;
